import { throttle } from 'lodash'

interface FitScaleOption {
	width?: number
	height?: number
	scaleDom: HTMLDivElement | null
	callback?: (scale: { width: number; height: number }) => void
}

export const calcScaleRate = (option: FitScaleOption) => {
	const { width = 1920, height = 1080, scaleDom = null, callback } = option
	// 画布尺寸（px）
	const baseWidth = width
	const baseHeight = height

	// 默认缩放值
	const scale = {
		width: 1,
		height: 1,
	}

	// 需保持的比例
	const baseProportion = parseFloat((baseWidth / baseHeight).toFixed(5))
	// 计算缩放比例
	const calcRate = () => {
		// 当前屏幕宽高比
		const currentRate = parseFloat(
			(window.innerWidth / window.innerHeight).toFixed(5),
		)

		if (scaleDom) {
			if (currentRate > baseProportion) {
				// 当前屏幕宽高比大于需保持的比例，表示宽度更宽
				scale.width = parseFloat(
					((window.innerHeight * baseProportion) / baseWidth).toFixed(5),
				)
				scale.height = parseFloat((window.innerHeight / baseHeight).toFixed(5))
				scaleDom.style.transform = `scale(${scale.width}, ${scale.height})`
			} else {
				// 当前屏幕宽高比小于需保持的比例，表示高度更高
				scale.width = parseFloat(
					(window.innerWidth / baseProportion / baseHeight).toFixed(5),
				)
				scale.height = parseFloat((window.innerWidth / baseWidth).toFixed(5))
				scaleDom.style.transform = `scale(${scale.width}, ${scale.height})`
			}
			if (callback) callback(scale)
		}
	}

	const resize = throttle(() => {
		calcRate()
	}, 200)

	const windowResize = () => {
		window.addEventListener('resize', resize)
	}

	const removeWindowResize = () => {
		window.removeEventListener('resize', resize)
	}

	return {
		calcRate,
		windowResize,
		removeWindowResize,
	}
}
